const axios = require('axios');
const https = require('https');
const tough = require('tough-cookie');
const { promisify } = require('util');

/*环境变量:fwkp_zm，格式账号#密码。多账号换行
  代理变量:fwkp_dl，返回选txt，协议为http/https
  网站:http://1403540.8-8.cc
*/

// 禁用HTTPS证书验证
const httpsAgent = new https.Agent({
    rejectUnauthorized: false
});

// 读取环境变量
const ACCOUNTS = process.env.fwkp_zm ? process.env.fwkp_zm.split('\n').filter(Boolean) : [];
const PROXY_API = process.env.fwkp_dl || '';
const LOGIN_URL = 'https://1403540.8-8.cc/user/ajax.php?act=login';
const SIGN_URL = 'https://1403540.8-8.cc/user/ajax_user.php?act=qiandao';
const LOGIN_PAGE_URL = 'https://1403540.8-8.cc/user/login.php';
const QIANDAO_PAGE_URL = 'https://1403540.8-8.cc/user/qiandao.php';

// UA列表（匹配抓包设备）
const UA_LIST = [
    'Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Mobile/15E148 Safari/604.1'
];

// 随机获取UA
function getRandomUA(usedUAs) {
    const availableUAs = UA_LIST.filter(ua => !usedUAs.includes(ua));
    const randomUA = availableUAs.length > 0 
        ? availableUAs[Math.floor(Math.random() * availableUAs.length)]
        : UA_LIST[Math.floor(Math.random() * UA_LIST.length)];
    usedUAs.push(randomUA);
    return randomUA;
}

// 延迟函数（仅保留必要延迟）
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 获取代理
async function getProxy(accountAlias) {
    if (!PROXY_API) {
        console.log(`[${accountAlias}] 未配置代理API地址`);
        return null;
    }
    try {
        const response = await axios.get(PROXY_API, {
            httpsAgent,
            timeout: 10000,
            responseType: 'text'
        });

        const responseData = typeof response.data === 'string' ? response.data : String(response.data);
        const proxies = responseData.split('\n')
            .map(proxy => {
                proxy = proxy.trim().replace(/\r/g, '');
                if (proxy && !proxy.startsWith('http://') && !proxy.startsWith('https://')) {
                    return `http://${proxy}`;
                }
                return proxy;
            })
            .filter(proxy => proxy && (proxy.startsWith('http://') || proxy.startsWith('https://')));
        
        if (proxies.length === 0) {
            console.log(`[${accountAlias}] 未获取到有效代理`);
            return null;
        }
        const randomProxy = proxies[Math.floor(Math.random() * proxies.length)];
        const [protocol, ipPort] = randomProxy.split('://');
        const [host, port] = ipPort.split(':');
        return {
            protocol,
            host,
            port: parseInt(port)
        };
    } catch (error) {
        console.log(`[${accountAlias}] 获取代理失败: ${error.message}`);
        return null;
    }
}

// 构建核心请求头
function buildHeaders(referer, ua, isLogin = false) {
    const baseHeaders = {
        'User-Agent': ua,
        'Referer': referer,
        'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-store, no-cache, must-revalidate',
        'Pragma': 'no-cache'
    };

    if (isLogin) {
        return {
            ...baseHeaders,
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://1403540.8-8.cc',
            'X-Requested-With': 'XMLHttpRequest'
        };
    }

    return {
        ...baseHeaders,
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'X-Requested-With': 'XMLHttpRequest'
    };
}

// 登录（仅提取签到所需参数：核心Cookie）
async function loginForSignParams(accountAlias, account, password, proxy, ua) {
    const cookieJar = new tough.CookieJar();
    const setCookie = promisify(cookieJar.setCookie).bind(cookieJar);
    const getCookieString = promisify(cookieJar.getCookieString).bind(cookieJar);

    try {
        const axiosInstance = axios.create({
            httpsAgent,
            withCredentials: true,
            proxy: proxy || undefined,
            transformResponse: [data => data]
        });

        // 1. 仅获取初始Cookie（签到必需的PHPSESSID、mysid）
        const loginPageRes = await axiosInstance.get(LOGIN_PAGE_URL, {
            headers: buildHeaders('https://1403540.8-8.cc/', ua),
            validateStatus: () => true
        });
        if (loginPageRes.headers['set-cookie']) {
            for (const cookie of loginPageRes.headers['set-cookie']) {
                await setCookie(cookie, LOGIN_PAGE_URL);
            }
        }
        await delay(500);

        // 2. 执行登录，获取签到核心参数（user_token）
        const loginParams = `user=${encodeURIComponent(account)}&pass=${encodeURIComponent(password)}`;
        const loginRes = await axiosInstance.post(LOGIN_URL, loginParams, {
            headers: {
                ...buildHeaders(LOGIN_PAGE_URL, ua, true),
                'Cookie': await getCookieString(LOGIN_URL),
                'Content-Length': Buffer.byteLength(loginParams, 'UTF-8')
            },
            validateStatus: (status) => true
        });

        // 解析响应
        let responseData;
        try {
            responseData = JSON.parse(loginRes.data);
        } catch (parseError) {
            const rawData = typeof loginRes.data === 'string' ? loginRes.data.substring(0, 100) : JSON.stringify(loginRes.data).substring(0, 100);
            console.log(`[${accountAlias}] 登录响应解析失败: ${rawData}...`);
            return null;
        }

        if (responseData.code === 0) {
            // 保存签到必需的Cookie（user_token + 初始Cookie）
            if (loginRes.headers['set-cookie']) {
                for (const cookie of loginRes.headers['set-cookie']) {
                    await setCookie(cookie, LOGIN_URL);
                }
            }
            // 提取签到所需的完整Cookie字符串
            const signCookie = await getCookieString(SIGN_URL);
            console.log(`[${accountAlias}] 登录成功，已提取签到参数`);
            return signCookie;
        } else {
            const errorCode = responseData.code !== undefined ? responseData.code : '无';
            const errorMsg = responseData.msg || '无具体错误描述';
            console.log(`[${accountAlias}] 登录失败 - 错误码: ${errorCode}, 原因: ${errorMsg}`);
            return null;
        }
    } catch (error) {
        let errorDetail = error.message;
        if (error.response) {
            errorDetail += `, 响应状态: ${error.response.status}`;
        }
        console.log(`[${accountAlias}] 登录异常 - 详情: ${errorDetail}`);
        return null;
    }
}

// 执行签到（修复数据类型错误）
async function signWithParams(accountAlias, signCookie, proxy, ua) {
    try {
        // 创建实例时禁用自动解析，确保获取原始数据
        const axiosInstance = axios.create({
            httpsAgent,
            withCredentials: true,
            proxy: proxy || undefined,
            timeout: 15000,
            transformResponse: [data => data] // 关键修复：保留原始响应数据
        });

        // 签到前仅加载签到页面初始化会话
        await axiosInstance.get(QIANDAO_PAGE_URL, {
            headers: {
                ...buildHeaders('https://1403540.8-8.cc/user/', ua),
                'Cookie': signCookie
            },
            validateStatus: () => true
        });
        await delay(300);

        // 执行签到
        const signRes = await axiosInstance.get(SIGN_URL, {
            headers: {
                ...buildHeaders(QIANDAO_PAGE_URL, ua),
                'Cookie': signCookie
            },
            validateStatus: (status) => true
        });

        // 处理响应数据（兼容字符串和对象类型）
        let signDataStr = signRes.data;
        if (typeof signDataStr !== 'string') {
            signDataStr = JSON.stringify(signDataStr); // 转为字符串
        }

        let signData;
        try {
            signData = JSON.parse(signDataStr);
        } catch (e) {
            const rawData = signDataStr.substring(0, 100);
            console.log(`[${accountAlias}] 签到响应解析失败: ${rawData}...`);
            return;
        }
        const signMsg = signData.msg || '签到结果未知';
        console.log(`[${accountAlias}] 签到结果: ${signMsg}`);
    } catch (error) {
        let errorDetail = error.message;
        if (error.response) {
            errorDetail += `, 响应状态: ${error.response.status}`;
        }
        console.log(`[${accountAlias}] 签到异常 - 详情: ${errorDetail}`);
    }
}

// 主程序（精简流程）
async function main() {
    console.log('凤舞卡铺签到脚本开始执行...');
    console.log(`共检测到 ${ACCOUNTS.length} 个账号`);
    console.log('------------------------');

    const usedUAs = [];

    for (let i = 0; i < ACCOUNTS.length; i++) {
        const line = ACCOUNTS[i];
        const [account, password] = line.split('#');
        const accountAlias = `账号${i + 1}`;
        const ua = getRandomUA(usedUAs);

        if (!account || !password) {
            console.log(`[${accountAlias}] 账号格式错误 - 缺少账号或密码`);
            console.log('------------------------');
            continue;
        }

        console.log(`[${accountAlias}] 正在获取代理...`);
        const proxy = await getProxy(accountAlias);
        if (proxy) {
            console.log(`[${accountAlias}] 使用代理: ${proxy.protocol}://${proxy.host}:${proxy.port}`);
        } else {
            console.log(`[${accountAlias}] 无可用代理，将直接请求`);
        }

        // 核心流程：登录提取参数 → 执行签到
        const signCookie = await loginForSignParams(accountAlias, account, password, proxy, ua);
        if (signCookie) {
            await signWithParams(accountAlias, signCookie, proxy, ua);
        }
        await delay(1500);
        console.log('------------------------');
    }

    console.log('签到脚本执行完毕！');
}

main();
